package cn.qdhlm.frontendprocessor.common.helper;


import cn.qdhlm.frontendprocessor.common.util.ComUtil;
import cn.qdhlm.frontendprocessor.common.util.JsonUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Name: HttpHelper
 * @Description: HttpHelper
 * @Author: jiangcs
 **/
@Log4j2
@Component
public class HttpHelper {
    @Autowired
    private CloseableHttpClient httpClient;
    private static CloseableHttpClient httpClientSta;

    @PostConstruct
    public void init() {
        httpClientSta = this.httpClient;
    }

    /**
     * doPost4Json
     *
     * @param url
     * @param headerMap
     * @param urlMap
     * @param bodyMap
     * @return
     * @throws Exception
     */
    public static String doPost4Json(String url, Map<String, String> headerMap, Map<String, Object> urlMap, Map<String, Object> bodyMap) throws Exception {
        // 获取URI，拼加 参数
        URIBuilder uriBuilder = new URIBuilder(url);
        if (urlMap != null && urlMap.size() > 0) {
            for (String key : urlMap.keySet()) {
                uriBuilder.setParameter(key, ComUtil.safeString(urlMap.get(key)));
            }
        }
        URI uri = uriBuilder.build();

        // 发送 POST 请求
        HttpPost httpPost = new HttpPost(uri);

        // Header参数
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }

        // Body参数
        JSONObject jsonObject = new JSONObject();
        if (bodyMap != null && bodyMap.size() > 0) {
            for (String key : bodyMap.keySet()) {
                jsonObject.put(key, bodyMap.get(key));
            }
        }
        httpPost.setEntity(new StringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));

        log.info("doPost4Json: url => {}", url);
        log.info("doPost4Json: headerMap => {}", JsonUtil.safeJsonStr(headerMap));
        log.info("doPost4Json: urlMap => {}", JsonUtil.safeJsonStr(urlMap));
        log.info("doPost4Json: bodyMap => {}", JsonUtil.safeJsonStr(bodyMap));

        CloseableHttpResponse response = httpClientSta.execute(httpPost);
        HttpEntity entity = response.getEntity();
        try {
            if (entity != null) {
                String result = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                log.info("doPost4Json: result => {}", result);
                return result;
            }
        } finally {
            if (entity != null) {
                EntityUtils.consume(entity);
            }
            response.close();
        }
        return null;
    }

    public static Integer doDelete(String url, Map<String, String> headerMap, Map<String, String> urlMap) throws Exception {
        // 获取URI，拼加 参数
        URIBuilder uriBuilder = new URIBuilder(url);
        if (urlMap != null && urlMap.size() > 0) {
            for (String key : urlMap.keySet()) {
                uriBuilder.setParameter(key, urlMap.get(key));
            }
        }
        URI uri = uriBuilder.build();

        log.info("doDelete: url => {}", url);
        log.info("doDelete: headerMap => {}", JsonUtil.safeJsonStr(headerMap));
        log.info("doDelete: urlMap => {}", JsonUtil.safeJsonStr(urlMap));

        // 发送 POST 请求
        HttpDelete httpDelete = new HttpDelete(uri);

        // Header参数
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                httpDelete.addHeader(key, headerMap.get(key));
            }
        }

        CloseableHttpResponse response = httpClientSta.execute(httpDelete);
        try {
            StatusLine statusLine = response.getStatusLine();
            log.info("doDelete: result => {}", JsonUtil.safeJsonStr(statusLine));
            return statusLine.getStatusCode();
        } finally {
            response.close();
        }
    }
}
